// JavaScript Document
function getloc(){
	navigator.geolocation.getCurrentPosition(
		function(pos){
			getWeather(',,,'+pos.coords.latitude*1000000+','+pos.coords.longitude*1000000);
		},
		function(err){
			getloc_ip();
		},{timeout:5000}
	);
};
function getloc_ip(){
	$.getScript('http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=js');
	if (window.remote_ip_info && window.remote_ip_info.city){
		getWeather(window.remote_ip_info.city);
	} else {
		if (window.retry_time2<2){
			window.retry_time2++;
			setTimeout('getloc_ip();',1000);
		} else {
			getWeather('error');
		};
	};
};
function getWeather(_loc){
	if (_loc=='error'){
		if ($('#no_loc').css('display')=='block'){
			$('#loc_err').show();
			$('#loc_submit').show();
		};
		$('#error').hide();
		$('#no_loc').show();
		$('#startup').fadeOut('fast');
		exit();
	};
	$.getScript('http://api.aq741.com/getWeather.aq?locale='+_loc,
	function(a,b){
		if (window._w && window._w.weather.problem_cause){
			getWeather('error');
		} else if ((!window._w) || _w === false || b!='success' || !_w.weather.current_conditions){
			if (window.retry_time<2){
				window.retry_time++;
				window._loc = _loc;
				setTimeout('getWeather(window._loc);',2000);
			} else {
				$('#error').show();
				$('#no_loc').hide();
				$('#startup').fadeOut('fast');
			};
		} else {
			localStorage.wt_locale = _loc;
			$('#no_loc').hide();
			$('body').css('background','#0A1D3B');
			if (_w.weather.forecast_information.city['@attributes'].data!=''){
				$('#header').html(_w.weather.forecast_information.city['@attributes'].data);
			}
			$('#startup').fadeOut('fast');
			//
			tmp = _w.weather.current_conditions;
			$('#info1 h2').html(tmp.temp_c['@attributes'].data+'°');
			$('#info1 h4').html(tmp.condition['@attributes'].data);
			$('#info1 h5').html(tmp.wind_condition['@attributes'].data);
			tmp = _w.weather.forecast_conditions[0];
			$('#info2 h3').html(tmp.high['@attributes'].data+'°/'+tmp.low['@attributes'].data+'°');
			$('#info2 h4').html(tmp.condition['@attributes'].data);
			for (i=1;i<4;i++){
				tmp = _w.weather.forecast_conditions[i];
				$('#info'+(i+2)+' h1').html(tmp.day_of_week['@attributes'].data);
				$('#info'+(i+2)+' h3').html(tmp.high['@attributes'].data+'°/'+tmp.low['@attributes'].data+'°');
				$('#info'+(i+2)+' h4').html(tmp.condition['@attributes'].data);
			};
		}
	});
}
$(function(){
	window.retry_time = 0;
	window.retry_time2 = 0;
	if (localStorage.wt_locale){
		getWeather(localStorage.wt_locale);
	} else if (navigator.geolocation){
		getloc();
	} else { getloc_ip(); };
	$('#loc_submit').click(function(){getWeather($('#loc_input').val());$(this).hide();});
});